package org.farng.mp3.id3;

import org.farng.mp3.AbstractMP3FragmentBody;
import org.farng.mp3.InvalidTagException;

import java.io.IOException;
import java.io.RandomAccessFile;


/**
 * DOCUMENT ME!
 *
 * @author Eric Farng Eric Farng
 * @version $Revision: 1.6 $
 */
public abstract class AbstractID3v2FrameBody extends AbstractMP3FragmentBody {
    public AbstractID3v2FrameBody() {}

    public AbstractID3v2FrameBody(AbstractID3v2FrameBody copyObject) {
        super(copyObject);
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     *
     * @todo Make this abstract. Can't do that yet because not all frame bodies
     *       have been finished.
     */
    public String getIdentifier() {
        return "";
    }

    /**
     * DOCUMENT ME!
     *
     * @param obj DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean equals(Object obj) {
        if ((obj instanceof AbstractID3v2FrameBody) == false) {
            return false;
        }

        return super.equals(obj);
    }

    /**
     * DOCUMENT ME!
     *
     * @param file DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     *
     * @throws IOException DOCUMENT ME!
     * @throws InvalidTagException DOCUMENT ME!
     */
    protected int readHeader(RandomAccessFile file)
                      throws IOException, InvalidTagException {
        int    size;
        byte[] buffer = new byte[3];

        if (use6ByteHeader()) {
            // read the 3 byte size
            file.read(buffer, 0, 3);
            size = (int) ((buffer[0] * Math.pow(2, 16)) + (buffer[1] * Math.pow(2, 8)) + buffer[2]);
        } else {
            // read the 4 byte size
            size = file.readInt();

            // we need to skip the flag bytes;
            file.skipBytes(2);
        }

        if (size == 0) {
            throw new InvalidTagException("Found empty frame");
        }

        if ((size <= 0) || (size > file.length())) {
            throw new InvalidTagException("Invalid size for Frame Body");
        }

        return size;
    }

    /**
     * DOCUMENT ME!
     *
     * @param file DOCUMENT ME!
     * @param size DOCUMENT ME!
     *
     * @throws IOException DOCUMENT ME!
     */
    protected void writeHeader(RandomAccessFile file, int size)
                        throws IOException {
        byte[] buffer = new byte[3];

        if (use6ByteHeader()) {
            // write the 3 byte size;
            buffer[0] = (byte) ((size & 0x00FF0000) >> 16);
            buffer[1] = (byte) ((size & 0x0000FF00) >> 8);
            buffer[2] = (byte) (size & 0x000000FF);
            file.write(buffer);
        } else {
            // write the 4 byte size;
            file.writeInt(size);

            // need to skip 2 flag bytes
            file.skipBytes(2);
        }
    }
}